package com.xncoding.valid.Resolver;

import com.xncoding.valid.Converter.CustomHttpMessageConverter;
import lombok.Getter;
import lombok.Setter;
import org.springframework.core.MethodParameter;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;

@Setter
@Getter
public class CustomHandlerMethodParameterResolver implements HandlerMethodArgumentResolver {

    private CustomHttpMessageConverter messageConverter ;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        return parameter.hasParameterAnnotation(Pack.class) ;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);

        ServletServerHttpRequest inputMessage = new ServletServerHttpRequest(request);

        return messageConverter.read((Class<?>)parameter.getNestedGenericParameterType(), inputMessage) ;
    }

}